<?php
/**
 * Created by PhpStorm.
 * User: Kevin
 * Date: 2019/6/18
 * Time: 18:25
 */
namespace app\api\controller;

use function Qiniu\explodeUpToken;
use think\Controller;
use think\Db;
use aliyun\OssDemo;
use OSS\OssClient;

class Dianxin extends Controller{
    // 定义配置项
    private $config=array(
        'NOTIFY_URL'         => 'http://csdl.jintianjifen.cn/admin/Dianxin/huidiao', // 接收支付状态的连接
        'NOTIFY_URLFWS'         => 'http://csdl.jintianjifen.cn/api/Weixin/huidiao2', // 接收支付状态的连接
    );
    private static $PRIVATE_KEY ='-----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAILcG3bJ2l1/lU5K
TN6/wCQv0mnj1d19ffOK3g92Ip9p8IuqTl4oTC/67ciJ31O21Ru8gCg8s0CCkS2o
zyNtFK2ngM0ChFqab29SKBc+xbGBhaZ2+YIhSpVbjMVfA7ffRQR85jgt4gpcDbtv
FXj4KlEiHbfumVyqSO5KoPY0tAt1AgMBAAECgYAqZQTAx0RnZh4I7ylYQOcO0i9o
/tcamr1jWWn3uF4fJ0M2/EXHW2bTZIgEoCYqCOGhyr/6STAJhkNid34kDALWg248
2BzVuP9dnt6nPR0hJTEkGoOO24k+yQLX2rtoYoEq7cBtZZMlxGDbKTzwb6MtlZ8/
g0fY2h+Dhi6EO12YAQJBAPiFkib1UIeEUP2BdoLxsL+bD2oXUVPELrGUNieC+7ZE
8kRTeMT3AcQW08R92esim0n6FGu2Aj5F3smAnzJNgSECQQCGzCeur3mzv9NOtyUg
F4tvtNjjHwoJngFbDGtdFQzTCY4WGOIP+iMgFWQrK3izqpCywGr00BuzSkZquTJt
1TvVAkBVXBt9Ahls0oe26va3tygMR8gdmnC2otWe7NdE7vph+oBz82+xx1116plG
DiwBVVudJyZIcLWIihshfuovLuvBAkBq3a3UIs/Ufo7SyAXJ1IC6FeEg5rm5eCfQ
/B6eFBMvuFKKGD4YtpFkXTElvHgb0GyZGk1xOw/K62a6M4rUYonlAkEA6FYBIdj5
zEkr6YYsShx15frEhf8yAjegJgrvZUPWHDGWs6lQmveDuIu3rkKOSgfVssghiABK
6NxE8U/eIKoPOA==
-----END PRIVATE KEY-----';
    private static $PUBLIC_KEY  ='-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCiYHZyQ6JGGFJiM3yQCKquxVs9
KCIBfnooLjiMg9ZLsnMk0ChRWV1bKhzJuMVdCdsfVxEhn0D2ydXDwxWhQA6PMCVg
G77WSifodUSwKp/Rcvj4aeDO1gUbHOYg7HseEV9/zIUrhXCZRpGPfQyPjfZ7yI9f
dI1GcTQ6dXl5tBc7zQIDAQAB
-----END PUBLIC KEY-----';
    public function aaa()
    {
//        $a = $this->uploadMediaTable('https://jintianjifen.oss-cn-shanghai.aliyuncs.com/1645107502190');
//        $bestpay = '{"merchantApplyType":"INDIVIDUAL_SELLER","merchantInputAuthContactReqDTOList":\'[{"contactType":"LEGAL","contactName":"\u8463\u519b","contactPhone":"18155055955","certificateType":"ID","certificateNo":"341124198407210010","validDate":"2037-11-01","contactFront":"group11\/M01\/F3\/65\/rBww6mIPNGWAcq62AAVyCokdA3g6926212","contactBack":"group11\/M01\/F3\/66\/rBww6mIPNGuAeZ3HAAZnx6uXpbk1914102","residentCity":"\u5b89\u5fbd\u7701\u6ec1\u5dde\u5e02"}]\',"merchantInputBankInfoReqDTO":\'{"perEntFlag":"PRIVATE","bankType":"DEBIT","bankAcctName":"\u8463\u519b","settleCardNo":"6228483158384627470","bankBranchName":"\u4e2d\u56fd\u519c\u4e1a\u94f6\u884c","settlementType":"BANK","phone":"18155055955","bankCode":"ABC"}\',"merchantInputBaseInfoReqDTO":\'{"loginNo":"18155055515","channel":"MERCHANT_CREATE_API","merchantName":"\u4e2a\u4f53\u6237\u8463\u519b","merchantShortName":"\u652f\u5206\u5b9d","mccCode":"5311","merchantSignboard":"group11\/M00\/F3\/5D\/rBww6mIPNEWAbqMFAApGUvndJtU9020941","merchantInterior":"group11\/M01\/F3\/64\/rBww6mIPNGGAamluAB8gGDPg4gE9508101","agentMerchantCode":"3178036282859431","recommendNo":"15961889367","businessAddress":"\u4e0a\u6d77\u4e0a\u6d77\u5e02\u5609\u5b9a\u533a\u9e64\u6816\u8def302\u53f7","businessServiceNo":"3178036418683176","provinceCode":"310000","cityCode":"310100","districtCode":"310114","manageType":"SERVICE_TRANSACTION"}\',"sign":"KMR/euNiYey/lhJCQ9LrjHUJaHI8HNndNWmalH7r3VBEywMcwp3dtA2KA2LzJ+NVveQmm1wP02kP+tnj3pFW5iSFfZcrfGBXw2HUK+IYxffGnaDcmOW1OWgzPuXVypQ7WDWUr3L/RLI4t5lhamSDhFbeEKWcIrPzZpjTgQdhrKg=","traceLogId":"shop16451635802"}';//接收xml数据的文件
//        $bestpayUrl = 'https://mapi.bestpay.com.cn/mapi/agent/merchantInputService/merchantIntegrateInput';//接收xml数据的文件
//        $response = $this->getJavaParam($bestpay,$bestpayUrl);
//        $result = json_decode($response,true);
//        if($result['success']) {
//
//            return json(['status' => 200, 'msg' => '申请已提交，请耐心等待审核~']);
//        }
//        return json(['status' => 100, 'msg' => 'error：' . $result['errorMsg']]);
//        dump($result);die;
    }
    /**
     * 上传图片
     *
     */
    public function uploadMediaTable($imgUrl,$ossType=1){
//        return 'group11/M00/90/F5/rBww6mIGVEGAYxcYABbk7o-ZnSo3493868';
        if($ossType == 1){
            import('aliyun.autoload', EXTEND_PATH);
//        $imgUrl = 'https://csdl.jintianjifen.cn/钱到啦业务特约商户服务协议.pdf';
            $accessKeyId = "LTAI9ltsS4tONPhv";
            $accessKeySecret = "PdQsbzveOa2JVVya7WNcfNOZoutwjM";
            // Endpoint以杭州为例，其它Region请按实际情况填写。
            $endpoint = "oss-cn-shanghai.aliyuncs.com";
            // 填写Bucket名称。
            $bucket= "jintianjifen";
            // 填写不包含Bucket名称在内的Object完整路径，例如testfolder/exampleobject.txt。
            $imgArr = explode('/',$imgUrl);
            $object = end($imgArr);
            // 下载Object到本地文件，并保存到指定的本地路径中。如果指定的本地文件存在会覆盖，不存在则新建。
            //// 如果未指定本地路径，则下载后的文件默认保存到示例程序所属项目对应本地路径中。
            $loadName = time() . rand(10000,99999) . '.jpg';
            $localfile = ROOT_PATH . "public/excel/" . $loadName;
            $options = array(
                OssClient::OSS_FILE_DOWNLOAD => $localfile
            );
            // 使用try catch捕获异常。如果捕获到异常，则说明下载失败；如果没有捕获到异常，则说明下载成功。
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $ossClient->getObject($bucket, $object, $options);
            $picData = base64EncodeImage ($localfile);
        }else{
            $picData = base64EncodeImage ($imgUrl);
        }

//        unlink($localfile);
//        dump($picData);die;
        //
        $javaData = ['base64' => $picData];
        $url = 'http://encrypt.seawxx.top:9999/digitalSign/reqPost';
        $header[] = "Content-type: application/json";//定义content-type为xml,注意是数组
        $javaRes = https_request($url, json_encode($javaData), $method = 'POST', $header);
        $javaRes = json_decode($javaRes,true);
        $javaRes = json_decode($javaRes['result'],true);
        return $javaRes['result'];
//        dump($javaRes);die;
//        return 'group11/M01/89/17/rBww6mIGJUGAU6xvABbk7o-ZnSo3283006';
////         = 'https://jintianjifen.oss-cn-shanghai.aliyuncs.com/1644462525109.jpg';
        $img_info = file_get_contents($imgUrl . '?x-oss-process=image/info');
        $img_info = json_decode($img_info,true);
        if($img_info['FileSize']['value'] > 2000000) $imgUrl = $imgUrl . '?x-oss-process=image/quality,Q_50';
        $picData = base64EncodeImage ($imgUrl);
        $config=array(
            'picData'=> $picData,
            'requestSystem'=>'QTSHPAY',
            'traceLogId'=>'open' . time() . rand(10000,99999),
        );
        // 合并配置数据和订单数据
        $data=$config;
        $datastr = $this->arrayToStr($data);
        $strSign = $this->createSign($datastr);      //生成签名
        // 生成签名
        $data['sign']=$strSign;
        ksort($data);
        $xml=json_encode($data);
        $bestpayUrl = 'https://mapi.bestpay.com.cn/mapi/agent/merchantinput/uploadFiles';//接收xml数据的文件
        $result=$this->getJavaParam($xml,$bestpayUrl);
        $result = json_decode($result,true);
        return $result['result'];
    }
    /**
     * 翼支付进件之前
     */
    public function getData(){
        $feilv = [
            1 => '7',
            2 => '7.5',
            3 => '8',
            4 => '8.5',
            5 => '9',
            6 => '9.5',
            7 => '9.8',
        ];
        $user_id = input('user_id');
        $shop_id = input('shop_id');
        if(isset($user_id) && $user_id){
            $yet = Db::name('shop')->where('shop_user_id', $user_id)->find();
        }elseif (isset($shop_id) && $shop_id){
            $yet = Db::name('shop')->where('shop_id', $shop_id)->find();
            if(!$yet) return json(['status' => 100, 'msg' => '数据错误！！！']);
        }else{
            return json(['status' => 100, 'msg' => '接口错误！！！']);
        }

        if($yet) {
            $yet['shengName'] = '';
            $yet['cityName'] = '';
            $yet['quName'] = '';
            if($yet['shop_sheng_id']) $yet['shengName'] = Db::name('area')->where('district_id', $yet['shop_sheng_id'])->value('district');
            if($yet['shop_city_id']) $yet['cityName'] = Db::name('area')->where('district_id', $yet['shop_city_id'])->value('district');
            if($yet['shop_qu_id']) $yet['quName'] = Db::name('area')->where('district_id', $yet['shop_qu_id'])->value('district');
            if(!$yet['shop_ratio']){
                $yet['shop_ratio'] = 8;
            }else{
                $yet['shop_ratio'] = array_search($yet['shop_ratio'],$feilv);
            }
            return json(['status' => 200, 'msg' => $yet]);
        }
        $yet = Db::name('shop_empty')->where('shop_id', 1)->find();
        $yet['shop_user_id'] = $user_id;
//        $yet['shengName'] = '';
//        $yet['cityName'] = '';
//        $yet['quName'] = '';
        return json(['status' => 200, 'msg' => $yet]);
    }
    /**
     * 获取图片信息
     */
    public function getImageInfo(){
        $imgType = input('imgType');
        $image = input('image');
        $card1 = [];$card2 = [];$card3 = [];
        if($imgType == 1) $card1 = getImgInfoForWx('https://aip.baidubce.com/rest/2.0/ocr/v1/idcard',1,$image);
        if($imgType == 2) $card2 = getImgInfoForWx('https://aip.baidubce.com/rest/2.0/ocr/v1/idcard',2,$image);
        if($imgType == 3) $card3 = getImgInfoForWx('https://aip.baidubce.com/rest/2.0/ocr/v1/business_license',3,$image);
        $info = [
            'contactName' => '',
            'certificateNo' => '',
            'validDate' => '',
            'registrationNumber' => '',
            'licenseBeginDate' => '',
            'licenseEndDate' => '',
        ];
        if($card1 && isset($card1['姓名'])){
            $info['contactName'] = $card1['姓名']['words'];
            $info['certificateNo'] = $card1['公民身份号码']['words'];
        }
        if($card2 && isset($card2['失效日期'])){
            $a = $card2['失效日期']['words'] ?: '';
            $info['validDate'] = substr($a,0,4) . '-' . substr($a,4,2) . '-' . substr($a,6,2);
        }
        if($card3 && isset($card3['社会信用代码'])) $info['registrationNumber'] = $card3['社会信用代码']['words'];
        if($card3 && isset($card3['成立日期'])) $info['licenseBeginDate'] = $card3['成立日期']['words'];
        if($card3 && isset($card3['有效期'])) $info['licenseEndDate'] = $card3['有效期']['words'] == '长期' ? '2199-12-31' : $card3['有效期']['words'];
        return json(['status' => 200, 'msg' => $info]);
    }
    /**
     * 翼支付进件
     */
    public function bestPayJinjian(){
        extract(input());
        $feilv = [
            1 => '7',
            2 => '7.5',
            3 => '8',
            4 => '8.5',
            5 => '9',
            6 => '9.5',
            7 => '9.8',
            8 => '',
        ];
        set_time_limit(0);
        $user = Db::name('u_user')->where('user_id', $user_id)->find();
//        $user['user_phone'] = '18155055955';
        $admin = Db::name('admin')->where('area', $qu)->find();
        if (empty($admin)) {
            return json(['status' => 100, 'msg' => '当前区暂无代理' . $sheng . '>' . $city . '>'.$qu]);
        }
        $shop_ratio = $feilv[$shop_ratio];
        $traceLogId = "shop" . time() . $user_id;
        $rand = rand(100000, 999999);
        $shop = [
            'shop_user_id'        => $user_id,
            'shop_account'        => $user['user_phone'],
            'shop_password'       => md5($rand),
            'shop_name'           => $merchantShortName,
            'shop_range'          => $businessScope, //TODO：这个要必填
            'shop_remark'         => '',
            'shop_contact'        => $user['user_phone'],
            'shop_address'        => $businessAddress,
            'shop_hand_img'       => $paramValue,
            'shop_facade_img'     => $contactFront,
            'shop_ldentity_img'   => $contactBack,
            'shop_sheng_id'       => $sheng,
            'shop_city_id'        => $city,
            'shop_time'           => date('Y-m-d H:i:s'),
            'shop_qu_id'          => $qu,
            'shop_lon'            => $lon,
            'shop_lat'            => $lat,
            'shop_superior_agent' => $admin['id'],
//            'shop_attestation'    => 3,
            'shop_rand'           => $rand,
            'shop_ratio'           => $shop_ratio,
            //-------------------------------------------
            'traceLogId'           => $traceLogId,
            'merchantApplyType'           => $merchantApplyType,
            'merchantName'           => $merchantName,
            'merchantShortName'           => $merchantShortName,
            'mccCode'           => $mccCode,
            'mccCodeName'           => $mccCodeName,
            'merchantSignboard'           => $merchantSignboard,
            'merchantInterior'           => $merchantInterior,
            'businessAddress'           => $businessAddress,
            'bankAcctName'           => $bankAcctName ?: '',
            'settleCardNo'           => $settleCardNo,
            'bankBranchName'           => $bankBranchName,
            'phone'           => $phone,
            'contactName'           => $contactName,
            'contactPhone'           => $contactPhone,
            'certificateNo'           => $certificateNo,
            'validDate'           => $validDate,
            'contactFront'           => $contactFront,
            'contactBack'           => $contactBack,
            'residentCity'           => $residentCity,
            'businessScope'           => $businessScope,
        ];
//        Db::startTrans();
//        try {
//            $yet = Db::name('shop')->where('shop_user_id', $user_id)->find();
//            if (!empty($yet)) {
//                Db::name('shop')->where('shop_id', $yet['shop_id'])->update($shop);
//            } else {
//                $id = Db::name('shop')->insertGetId($shop);
//                Db::name('u_user')->where('user_id', $user_id)->setField('user_shop_id', $id);
//            }
//            Db::name('u_user')->where('user_id', $user_id)->update(['user_one_pay' => 4, 'user_edit_time' => date('Y-m-d H:i:s')]);
//            Db::commit();
//            return json(['status' => 200, 'msg' => '等待审核']);
//        } catch (\Exception $e) {
//            Db::rollback();
//            Log::record($e->getMessage(), 'error');
//            return json(['status' => 100, 'msg' => '提交失败']);
//        }
        if($baocun != 1) {
            $config = array(
                'traceLogId' => $traceLogId,
                'merchantApplyType' => $merchantApplyType, //
                'merchantInputBaseInfoReqDTO' => [
                    'loginNo' => $user['user_phone'], //手机号
                    'channel' => 'MERCHANT_CREATE_API',
                    'merchantName' => $merchantName, //商户全称：个体工商户和企业商户填写营业执照上的名称；小微：个体户+法人（个体户张三）
                    'merchantShortName' => $merchantShortName, //商户简称：填写商户名称简称或其他表明商户经营范围的简称
//                'businessScope' => '个体户董军', //营业范围：个体工商户和企业商户需要填写；必须包含在营业执照经营范围内；小微商户不需要填写
//                'provinceCode' => '', //省份编码
//                'cityCode' => '', //市编码
//                'districtCode' => '', //区编码
                    'mccCode' => $mccCode, //经营类目：小微商户签 PS11700 解决方案，个体工商户/企业商户签 PS10418解决方案。
//                'manageType' => $manageType, //经营类型
                    'merchantSignboard' => $this->uploadMediaTable($merchantSignboard), //fileID：门头照（代理商扩展人员/法人与门头合照）
                    'merchantInterior' => $this->uploadMediaTable($merchantInterior), //fileID：店内照
                    'agentMerchantCode' => '3178036282859431', //拓展代理商商户号
                    'recommendNo' => '15961889367', //拓展人手机号;拓展人信息需要高实(登录代理商管理平台批量导入)
                    'businessAddress' => $businessAddress, //商户实际经营详细地
                    'businessServiceNo' => '3178036418683176', //平台商户号
                ],
                'merchantInputBankInfoReqDTO' => [
                    'perEntFlag' => $merchantApplyType == 'COMPANY' ? 'PUBLIC' : 'PRIVATE', //企业类型商户需校验必须为对公类型
                    'bankType' => $merchantApplyType == 'COMPANY' ? 'BA' : 'DEBIT', //企业商户银行账户默认为 BA；个体商户和小微商户默认 DEBIT
                    'bankAcctName' => $bankAcctName, //对私结算填法人姓名 对公结算填商户全称
                    'settleCardNo' => $settleCardNo, //结算银行卡号
                    'bankBranchName' => $bankBranchName, //对私可填总行名称，对公需填写支行名称:
                    'settlementType' => 'BANK', //若填写则只能填写 BANK，填写后则会结算到银行卡
//                'cnapsNo' => 'DEBIT' , //银行联行号：对公结算必填，对私结算非必填
                    'phone' => $phone, //银行卡预留手机号(企业商户非必填)
//                'bankCode' => $bankCode , //银行编码；
//                'settlePic' => 'DEBIT' , //结算证明：企业商户必填。对私传银行卡正面照，对公传能证明账⼾真实有效的材料，如印鉴卡、转账凭证等；
                ],
                'merchantInputAuthContactReqDTOList' => [
                    [
                        'contactType' => 'LEGAL', //联系人类型：法人
                        'contactName' => $contactName, //联系人姓名：法人姓名
                        'contactPhone' => $contactPhone, //联系人电话（法人类型时不能为空）
                        'certificateType' => 'ID', //联系人证件类型：身份证
                        'certificateNo' => $certificateNo, //联系人证件号
                        'validDate' => $validDate, //联系人证件有效期：截止时间格式：(String)yyyy-MM-dd
                        'contactFront' => $this->uploadMediaTable($contactFront), //联系人证件正面照（类型是法人、受托人必填）
                        'contactBack' => $this->uploadMediaTable($contactBack), //联系人证件反面照（类型是法人、受托人必填）
                        'residentCity' => $residentCity, //联系人所在地址（类型是法人、受益人、受托人时必填）
                    ]
                ],
//            'merchantInputAuthIdentifyReqDTO'=>[
//                'businessCertificat' => $businessCertificat , //证照类型:LICENSE营业执照；MLICENS多证合一营业执照
//                'registrationNumber' => $registrationNumber , //证照编号
//                'licenseBeginDate' => $licenseBeginDate , //证件注册起始日期
//                'licenseEndDate' => $licenseEndDate , //证件截止日期
//                'registeredCry' => 'CNY' , //注册币种，默认人民币：CNY
//                'registeredCapital' => $registeredCapital , //注册资本金：单位：万元；企业必填，没有注册资本:填 0
//                'paramValue' => $this->uploadMediaTable($paramValue) , //营业执照地址（fileID）
//            ],
            );
        }
        $shengName = Db::table('up_area')->where('district_id',$sheng)->value('district');
        $shiName = Db::table('up_area')->where('district_id',$city)->value('district');
        $quName = Db::table('up_area')->where('district_id',$qu)->value('district');
        $zhixia = ['北京','天津','重庆','上海'];
        if(in_array($sheng,$zhixia)) {
            $config['merchantInputBaseInfoReqDTO']['businessAddress'] = $shiName . $quName . $businessAddress;
        }else{
            $config['merchantInputBaseInfoReqDTO']['businessAddress'] = $shengName . $shiName . $quName . $businessAddress;
        };
        $shengCode = Db::table('up_z_areacode')
            ->where('sheng','like',"%$shengName%")
            ->value('shengCode');
        $shiCode = Db::table('up_z_areacode')
            ->where('sheng','like',"%$shengName%")
            ->where('shi','like',"%$shiName%")
            ->value('shiCode');
        $quCode = Db::table('up_z_areacode')
            ->where('sheng','like',"%$shengName%")
            ->where('shi','like',"%$shiName%")
            ->where('qu','like',"%$quName%")
            ->value('quCode');
        if(!$shengCode || !$shiCode || !$quCode) {
            return json(['status' => 100, 'msg' => '省市区有误']);
        }else{
            $config['merchantInputBaseInfoReqDTO']['provinceCode'] = $shengCode;
            $config['merchantInputBaseInfoReqDTO']['cityCode'] = $shiCode;
            $config['merchantInputBaseInfoReqDTO']['districtCode'] = $quCode;
        }
        if($merchantApplyType != 'INDIVIDUAL_SELLER') {
            $config['merchantInputBaseInfoReqDTO']['businessScope'] = $businessScope;
        }else{
            $config['merchantInputBaseInfoReqDTO']['merchantName'] = '个体户' . $merchantName;
            $config['merchantInputBaseInfoReqDTO']['manageType'] = $manageType;
            //------------------------------------
            $shop['manageType'] = $manageType;
        }
        if($merchantApplyType != 'INDIVIDUAL_SELLER') {
            if($baocun != 1 && $merchantApplyType == 'COMPANY') {
                $bankdata = Db::name('z_allbank')
                    ->where('bank_name_zhi', $bankBranchName)
                    ->find();
                if ($bankdata) {
                    if ($merchantApplyType == 'COMPANY') $config['merchantInputBankInfoReqDTO']['cnapsNo'] = $bankdata['canpsNo'];
                    $config['merchantInputBankInfoReqDTO']['bankCode'] = $bankdata['bank_code'];
                } else {
                    return json(['status' => 100, 'msg' => '请填写正确的银行全称']);
                }
            }
            if($merchantApplyType == 'COMPANY') {
                if($baocun != 1){
                    $config['merchantInputBankInfoReqDTO']['settlePic'] = $this->uploadMediaTable($settlePic);
                }
                $shop['settlePic'] = $settlePic;
            }
            if($baocun != 1) {
                $config['merchantInputAuthIdentifyReqDTO'] = [
                    'businessCertificat' => $businessCertificat, //证照类型:LICENSE营业执照；MLICENS多证合一营业执照
                    'registrationNumber' => $registrationNumber, //证照编号
                    'licenseBeginDate' => $licenseBeginDate, //证件注册起始日期
                    'licenseEndDate' => $licenseEndDate == '无' ? '2199-12-31' : $licenseEndDate, //证件截止日期
                    'registeredCry' => 'CNY', //注册币种，默认人民币：CNY
                    'registeredCapital' => $merchantApplyType == 'COMPANY' ? $registeredCapital : '0', //注册资本金：单位：万元；企业必填，没有注册资本:填 0
                    'paramValue' => $this->uploadMediaTable($paramValue), //营业执照地址（fileID）
                ];
            }
            //------------------------------------
            $shop['registeredCapital'] = $merchantApplyType == 'COMPANY' ? $registeredCapital : '0';
            $shop['businessCertificat'] = $businessCertificat;
            $shop['registrationNumber'] = $registrationNumber;
            $shop['licenseBeginDate'] = $licenseBeginDate;
            $shop['licenseEndDate'] = $licenseEndDate == '无' ? '2199-12-31' : $licenseEndDate;
            $shop['paramValue'] = $paramValue;
        }
        if($merchantApplyType != 'COMPANY'){
            if($baocun != 1) {
                $bankBranchName = trim($bankBranchName,',');
                if(mb_strlen($bankBranchName) < 4) return json(['status' => 100, 'msg' => '请填写正确的银行名称']);
                $bankBranchName = str_replace("中国","",$bankBranchName);
                $bankdata = Db::name('z_allbank')
                    ->where('bank_name', 'like','%' . $bankBranchName . '%')
                    ->whereOr('bank_name_zhi', $bankBranchName)
                    ->find();
                if ($bankdata) {
                    $config['merchantInputBankInfoReqDTO']['bankCode'] = $bankdata['bank_code'];
                } else {
                    return json(['status' => 100, 'msg' => '请填写正确的银行名称']);
                }
            }
        }
        //-------------------------------------------------------------------------------------------------------
        $yet = Db::name('shop')->where('shop_user_id', $user_id)->find();
        if (!empty($yet)) {
            $dx_status = $yet['dx_status'];
            $shop_id = $yet['shop_id'];
            Db::name('shop')->where('shop_id', $yet['shop_id'])->update($shop);

        } else {
            $shop_id = Db::name('shop')->insertGetId($shop);
            Db::name('u_user')->where('user_id', $user_id)->setField('user_shop_id', $shop_id);
            $dx_status = 0;
        }
        if($baocun == 1) return json(['status' => 200, 'msg' => '可以下一步']);
//        if($baocun != 1) {
//            Db::name('u_user')->where('user_id', $user_id)->update(['user_one_pay' => 4, 'user_edit_time' => date('Y-m-d H:i:s')]);
//        }else{
//            return json(['status' => 200, 'msg' => '可以下一步']);
//        }
        //-------------------------------------------------------------------------------------------------------
//        return json(['status' => 100, 'msg' => '恭喜走通！！！！！']);
        // 合并配置数据和订单数据
        if($dx_status == 0 || $dx_status == 3){
            $data=$config;
            ksort($data);
            //---------------------------------------------
            $result2 = json_encode($data);
            Db::name('z_z_dianxin')->insert([
                'content' => 'dd>'.$result2
            ]);
            //---------------------------------------------
            $datastr = $this->arrayToStr($data);
            $datastr = urldecode($datastr);
            $strSign = $this->createSign($datastr);      //生成签名
            // 生成签名
            $data['sign']=$strSign;
            ksort($data);
            $xml=$this->arrayToStr2($data);
            $bestpayUrl = 'https://mapi.bestpay.com.cn/mapi/agent/merchantInputService/merchantIntegrateInput';//接收xml数据的文件
            $response=$this->getJavaParam($xml,$bestpayUrl);
            $result = json_decode($response,true);
            if($result['success']) {
                Db::name('u_user')->where('user_id', $user_id)->update(['user_one_pay' => 4, 'user_edit_time' => date('Y-m-d H:i:s')]);
                $javaRes=$this->getBackResult($response);
                if($javaRes['msg'] == 'success' && $javaRes['result']){
                    $result = explode('&',$javaRes['result']);
                    Db::name('shop')->where('shop_id', $shop_id)->update([
                        'shop_attestation' => 3,
                        'dx_status' => 1,
                        'applyNo' => explode('=',$result[0])[1],
                        'merchantCode' => explode('=',$result[1])[1],
                        'dx_mch_id' => explode('=',$result[1])[1]
                    ]);
                }
                return json(['status' => 200, 'msg' => '申请已提交，请耐心等待审核~']);
            }
            return json(['status' => 100, 'msg' => 'error：' . $result['errorMsg']]);
        }
        Db::name('shop')->where('shop_id', $shop_id)->update([
            'shop_attestation' => 3
        ]);
        Db::name('u_user')->where('user_id', $user_id)->update(['user_one_pay' => 4, 'user_edit_time' => date('Y-m-d H:i:s')]);
        return json(['status' => 200, 'msg' => '修改成功~']);
    }
    /**
     * 商户的翼支付进件
     */
    public function bestPayJinjianShop(){
        extract(input());
        $feilv = [
            1 => '7',
            2 => '7.5',
            3 => '8',
            4 => '8.5',
            5 => '9',
            6 => '9.5',
            7 => '9.8',
            8 => '',
        ];
        set_time_limit(0);
        $shopData = Db::name('shop')->where('shop_id', $shop_id)->find();
        $admin = Db::name('admin')->where('area', $qu)->find();
        if (empty($admin)) {
            return json(['status' => 100, 'msg' => '当前区暂无代理' . $sheng . '>' . $city . '>'.$qu]);
        }
        $shop_ratio = $feilv[$shop_ratio];
        $traceLogId = "shop" . time() . $shop_id;
        $shop = [
            'shop_name'           => $merchantShortName,
            'shop_range'          => $businessScope, //TODO：这个要必填
            'shop_remark'         => '',
            'shop_address'        => $businessAddress,
            'shop_hand_img'       => $paramValue,
            'shop_facade_img'     => $contactFront,
            'shop_ldentity_img'   => $contactBack,
            'shop_sheng_id'       => $sheng,
            'shop_city_id'        => $city,
            'shop_qu_id'          => $qu,
            'shop_lon'            => $lon,
            'shop_lat'            => $lat,
            'shop_superior_agent' => $admin['id'],
//            'shop_attestation'    => 3,
            'shop_ratio'           => $shop_ratio,
            //-------------------------------------------
            'traceLogId'           => $traceLogId,
            'merchantApplyType'           => $merchantApplyType,
            'merchantName'           => $merchantName,
            'merchantShortName'           => $merchantShortName,
            'mccCode'           => $mccCode,
            'mccCodeName'           => $mccCodeName,
            'merchantSignboard'           => $merchantSignboard,
            'merchantInterior'           => $merchantInterior,
            'businessAddress'           => $businessAddress,
            'bankAcctName'           => $bankAcctName ?: '',
            'settleCardNo'           => $settleCardNo,
            'bankBranchName'           => $bankBranchName,
            'phone'           => $phone,
            'contactName'           => $contactName,
            'contactPhone'           => $contactPhone,
            'certificateNo'           => $certificateNo,
            'validDate'           => $validDate,
            'contactFront'           => $contactFront,
            'contactBack'           => $contactBack,
            'residentCity'           => $residentCity,
            'businessScope'           => $businessScope,
        ];
//        Db::startTrans();
//        try {
//            $yet = Db::name('shop')->where('shop_user_id', $user_id)->find();
//            if (!empty($yet)) {
//                Db::name('shop')->where('shop_id', $yet['shop_id'])->update($shop);
//            } else {
//                $id = Db::name('shop')->insertGetId($shop);
//                Db::name('u_user')->where('user_id', $user_id)->setField('user_shop_id', $id);
//            }
//            Db::name('u_user')->where('user_id', $user_id)->update(['user_one_pay' => 4, 'user_edit_time' => date('Y-m-d H:i:s')]);
//            Db::commit();
//            return json(['status' => 200, 'msg' => '等待审核']);
//        } catch (\Exception $e) {
//            Db::rollback();
//            Log::record($e->getMessage(), 'error');
//            return json(['status' => 100, 'msg' => '提交失败']);
//        }
        if($baocun != 1 && $shopData['dx_status'] != 1 && $shopData['dx_status'] != 2) {
            $config = array(
                'traceLogId' => $traceLogId,
                'merchantApplyType' => $merchantApplyType, //
                'merchantInputBaseInfoReqDTO' => [
                    'loginNo' => $shopData['shop_account'], //手机号
                    'channel' => 'MERCHANT_CREATE_API',
                    'merchantName' => $merchantName, //商户全称：个体工商户和企业商户填写营业执照上的名称；小微：个体户+法人（个体户张三）
                    'merchantShortName' => $merchantShortName, //商户简称：填写商户名称简称或其他表明商户经营范围的简称
//                'businessScope' => '个体户董军', //营业范围：个体工商户和企业商户需要填写；必须包含在营业执照经营范围内；小微商户不需要填写
//                'provinceCode' => '', //省份编码
//                'cityCode' => '', //市编码
//                'districtCode' => '', //区编码
                    'mccCode' => $mccCode, //经营类目：小微商户签 PS11700 解决方案，个体工商户/企业商户签 PS10418解决方案。
//                'manageType' => $manageType, //经营类型
                    'merchantSignboard' => $this->uploadMediaTable($merchantSignboard), //fileID：门头照（代理商扩展人员/法人与门头合照）
                    'merchantInterior' => $this->uploadMediaTable($merchantInterior), //fileID：店内照
                    'agentMerchantCode' => '3178036282859431', //拓展代理商商户号
                    'recommendNo' => '15961889367', //拓展人手机号;拓展人信息需要高实(登录代理商管理平台批量导入)
                    'businessAddress' => $businessAddress, //商户实际经营详细地
                    'businessServiceNo' => '3178036418683176', //平台商户号
                ],
                'merchantInputBankInfoReqDTO' => [
                    'perEntFlag' => $merchantApplyType == 'COMPANY' ? 'PUBLIC' : 'PRIVATE', //企业类型商户需校验必须为对公类型
                    'bankType' => $merchantApplyType == 'COMPANY' ? 'BA' : 'DEBIT', //企业商户银行账户默认为 BA；个体商户和小微商户默认 DEBIT
                    'bankAcctName' => $bankAcctName, //对私结算填法人姓名 对公结算填商户全称
                    'settleCardNo' => $settleCardNo, //结算银行卡号
                    'bankBranchName' => $bankBranchName, //对私可填总行名称，对公需填写支行名称:
                    'settlementType' => 'BANK', //若填写则只能填写 BANK，填写后则会结算到银行卡
//                'cnapsNo' => 'DEBIT' , //银行联行号：对公结算必填，对私结算非必填
                    'phone' => $phone, //银行卡预留手机号(企业商户非必填)
//                'bankCode' => $bankCode , //银行编码；
//                'settlePic' => 'DEBIT' , //结算证明：企业商户必填。对私传银行卡正面照，对公传能证明账⼾真实有效的材料，如印鉴卡、转账凭证等；
                ],
                'merchantInputAuthContactReqDTOList' => [
                    [
                        'contactType' => 'LEGAL', //联系人类型：法人
                        'contactName' => $contactName, //联系人姓名：法人姓名
                        'contactPhone' => $contactPhone, //联系人电话（法人类型时不能为空）
                        'certificateType' => 'ID', //联系人证件类型：身份证
                        'certificateNo' => $certificateNo, //联系人证件号
                        'validDate' => $validDate, //联系人证件有效期：截止时间格式：(String)yyyy-MM-dd
                        'contactFront' => $this->uploadMediaTable($contactFront), //联系人证件正面照（类型是法人、受托人必填）
                        'contactBack' => $this->uploadMediaTable($contactBack), //联系人证件反面照（类型是法人、受托人必填）
                        'residentCity' => $residentCity, //联系人所在地址（类型是法人、受益人、受托人时必填）
                    ]
                ],
//            'merchantInputAuthIdentifyReqDTO'=>[
//                'businessCertificat' => $businessCertificat , //证照类型:LICENSE营业执照；MLICENS多证合一营业执照
//                'registrationNumber' => $registrationNumber , //证照编号
//                'licenseBeginDate' => $licenseBeginDate , //证件注册起始日期
//                'licenseEndDate' => $licenseEndDate , //证件截止日期
//                'registeredCry' => 'CNY' , //注册币种，默认人民币：CNY
//                'registeredCapital' => $registeredCapital , //注册资本金：单位：万元；企业必填，没有注册资本:填 0
//                'paramValue' => $this->uploadMediaTable($paramValue) , //营业执照地址（fileID）
//            ],
            );
        }
        $shengName = Db::table('up_area')->where('district_id',$sheng)->value('district');
        $shiName = Db::table('up_area')->where('district_id',$city)->value('district');
        $quName = Db::table('up_area')->where('district_id',$qu)->value('district');
        $zhixia = ['北京','天津','重庆','上海'];
        if(in_array($sheng,$zhixia)) {
            $config['merchantInputBaseInfoReqDTO']['businessAddress'] = $shiName . $quName . $businessAddress;
        }else{
            $config['merchantInputBaseInfoReqDTO']['businessAddress'] = $shengName . $shiName . $quName . $businessAddress;
        };
        $shengCode = Db::table('up_z_areacode')
            ->where('sheng','like',"%$shengName%")
            ->value('shengCode');
        $shiCode = Db::table('up_z_areacode')
            ->where('sheng','like',"%$shengName%")
            ->where('shi','like',"%$shiName%")
            ->value('shiCode');
        $quCode = Db::table('up_z_areacode')
            ->where('sheng','like',"%$shengName%")
            ->where('shi','like',"%$shiName%")
            ->where('qu','like',"%$quName%")
            ->value('quCode');
        if(!$shengCode || !$shiCode || !$quCode) {
            return json(['status' => 100, 'msg' => '省市区有误']);
        }else{
            $config['merchantInputBaseInfoReqDTO']['provinceCode'] = $shengCode;
            $config['merchantInputBaseInfoReqDTO']['cityCode'] = $shiCode;
            $config['merchantInputBaseInfoReqDTO']['districtCode'] = $quCode;
        }
        if($merchantApplyType != 'INDIVIDUAL_SELLER') {
            $config['merchantInputBaseInfoReqDTO']['businessScope'] = $businessScope;
        }else{
            $config['merchantInputBaseInfoReqDTO']['merchantName'] = '个体户' . $merchantName;
            $config['merchantInputBaseInfoReqDTO']['manageType'] = $manageType;
            //------------------------------------
            $shop['manageType'] = $manageType;
        }
        if($merchantApplyType != 'INDIVIDUAL_SELLER') {
            if($baocun != 1 && $merchantApplyType == 'COMPANY') {
                $bankdata = Db::name('z_allbank')
                    ->where('bank_name_zhi', $bankBranchName)
                    ->find();
                if ($bankdata) {
                    if ($merchantApplyType == 'COMPANY') $config['merchantInputBankInfoReqDTO']['cnapsNo'] = $bankdata['canpsNo'];
                    $config['merchantInputBankInfoReqDTO']['bankCode'] = $bankdata['bank_code'];
                } else {
                    return json(['status' => 100, 'msg' => '请填写正确的银行全称']);
                }
            }
            if($merchantApplyType == 'COMPANY') {
                if($baocun != 1){
                    $config['merchantInputBankInfoReqDTO']['settlePic'] = $this->uploadMediaTable($settlePic);
                }
                $shop['settlePic'] = $settlePic;
            }
            if($baocun != 1) {
                $config['merchantInputAuthIdentifyReqDTO'] = [
                    'businessCertificat' => $businessCertificat, //证照类型:LICENSE营业执照；MLICENS多证合一营业执照
                    'registrationNumber' => $registrationNumber, //证照编号
                    'licenseBeginDate' => $licenseBeginDate, //证件注册起始日期
                    'licenseEndDate' => $licenseEndDate == '无' ? '2199-12-31' : $licenseEndDate, //证件截止日期
                    'registeredCry' => 'CNY', //注册币种，默认人民币：CNY
                    'registeredCapital' => $merchantApplyType == 'COMPANY' ? $registeredCapital : '0', //注册资本金：单位：万元；企业必填，没有注册资本:填 0
                    'paramValue' => $this->uploadMediaTable($paramValue), //营业执照地址（fileID）
                ];
            }
            //------------------------------------
            $shop['registeredCapital'] = $merchantApplyType == 'COMPANY' ? $registeredCapital : '0';
            $shop['businessCertificat'] = $businessCertificat;
            $shop['registrationNumber'] = $registrationNumber;
            $shop['licenseBeginDate'] = $licenseBeginDate;
            $shop['licenseEndDate'] = $licenseEndDate == '无' ? '2199-12-31' : $licenseEndDate;
            $shop['paramValue'] = $paramValue;
        }
        if($merchantApplyType != 'COMPANY'){
            if($baocun != 1) {
                $bankBranchName = trim($bankBranchName,',');
                if(mb_strlen($bankBranchName) < 4) return json(['status' => 100, 'msg' => '请填写正确的银行名称']);
                $bankBranchName = str_replace("中国","",$bankBranchName);
                $bankdata = Db::name('z_allbank')
                    ->where('bank_name', 'like','%' . $bankBranchName . '%')
                    ->whereOr('bank_name_zhi', $bankBranchName)
                    ->find();
                if ($bankdata) {
                    $config['merchantInputBankInfoReqDTO']['bankCode'] = $bankdata['bank_code'];
                } else {
                    return json(['status' => 100, 'msg' => '请填写正确的银行名称']);
                }
            }
        }
        //-------------------------------------------------------------------------------------------------------
        $dx_status = $shopData['dx_status'];
        Db::name('shop')->where('shop_id', $shop_id)->update($shop);
        if($baocun == 1 || $shop_id == 1) return json(['status' => 200, 'msg' => '可以下一步']);
//        if($baocun != 1) {
//            Db::name('u_user')->where('user_id', $user_id)->update(['user_one_pay' => 4, 'user_edit_time' => date('Y-m-d H:i:s')]);
//        }else{
//            return json(['status' => 200, 'msg' => '可以下一步']);
//        }
        //-------------------------------------------------------------------------------------------------------
//        return json(['status' => 100, 'msg' => '恭喜走通！！！！！']);
        // 合并配置数据和订单数据
        if($dx_status == 0 || $dx_status == 3){
            $data=$config;
            ksort($data);
            //---------------------------------------------
            $result2 = json_encode($data);
            Db::name('z_z_dianxin')->insert([
                'content' => 'shop>'.$result2
            ]);
            //---------------------------------------------
            $datastr = $this->arrayToStr($data);
            $datastr = urldecode($datastr);
            $strSign = $this->createSign($datastr);      //生成签名
            // 生成签名
            $data['sign']=$strSign;
            ksort($data);
            $xml=$this->arrayToStr2($data);
            $bestpayUrl = 'https://mapi.bestpay.com.cn/mapi/agent/merchantInputService/merchantIntegrateInput'; //接收xml数据的文件
            $response=$this->getJavaParam($xml,$bestpayUrl);
            $result = json_decode($response,true);
            if($result['success']) {
                $javaRes=$this->getBackResult($response);
                if($javaRes['msg'] == 'success' && $javaRes['result']){
                    $result = explode('&',$javaRes['result']);
                    Db::name('shop')->where('shop_id', $shop_id)->update([
                        'dx_status' => 1,
                        'applyNo' => explode('=',$result[0])[1],
                        'merchantCode' => explode('=',$result[1])[1],
                        'dx_mch_id' => explode('=',$result[1])[1]
                    ]);
                }
                return json(['status' => 200, 'msg' => '申请已提交，请耐心等待审核~']);
            }
            return json(['status' => 100, 'msg' => 'error：' . $result['errorMsg']]);
        }
        return json(['status' => 200, 'msg' => '修改成功~']);
    }

    public function get_mccCode(){
        $type =$_POST['type'];
        $data = Db::name('z_codecc')
            ->where('type', $type)
            ->field('code,name')
            ->order('paixu asc')
            ->select();

        return json(['status' => 200, 'msg' => $data]);
    }
    /**
     *查询
     */
    public function chaxun()
    {
        $datas = Db::name('shop')->where('dx_status',1)
            ->field('shop_id,shop_attestation,shop_user_id,shop_account,traceLogId,dx_err')
            ->select();
//        dump($datas);die;
        if($datas){
            foreach ($datas as $k => $v){
                $config=array(
                    'traceLogId'=> 'cx' . $v['traceLogId'],
//                    'loginNo'=> '18155055955'
                    'loginNo'=> $v['shop_account']
                );
                // 合并配置数据和订单数据
                $data=$config;
                ksort($data);
                $datastr = $this->arrayToStr($data);
                $strSign = $this->createSign($datastr);      //生成签名
                // 生成签名
                $data['sign']=$strSign;
                ksort($data);
                $xml=json_encode($data);
                $bestpayUrl = 'https://mapi.bestpay.com.cn/mapi/agent/merchantInputService/queryMerchantInputStatus';//接收xml数据的文件
                $response=$this->getJavaParam($xml,$bestpayUrl);
                $javaRes=$this->getBackResult($response);
//                dump($javaRes);die;
                if($javaRes['msg'] == 'success' && $javaRes['result']){
                    parse_str($javaRes['result']);
//                    dump($javaRes['result']);die;
                    if($auditStatus=='AUDITED_SUCCESS' || $auditStatus=='ENABLE'){
                        Db::name('shop')->where('shop_id',$v['shop_id'])->update([
                            'dx_status' => 2,
                            'dx_err' => ''
                        ]);
                    }else if($auditStatus=='OPEN_ACCOUNT_FAIL' || $auditStatus=='AUDITED_FAIL'){
                        if($v['shop_attestation'] != 2){
                            Db::name('shop')->where('shop_id',$v['shop_id'])->update([
                                'shop_attestation' => 4,
                                'dx_status' => 3,
                                'dx_err' => $failureReason
                            ]);
                            Db::name('u_user')->where('user_id',$v['shop_user_id'])->update([
                                'user_one_pay' => 5
                            ]);
                        }else{
                            Db::name('shop')->where('shop_id',$v['shop_id'])->update([
                                'dx_status' => 3,
                                'dx_err' => $failureReason
                            ]);
                        }

                    }else{
                        if(isset($failureReason) && $v['dx_err'] != $failureReason){
                            Db::name('shop')->where('shop_id',$v['shop_id'])->update([
                                'dx_err' => $failureReason
                            ]);
                        }
                    }
                }
            }
        }
        exit();
    }
    /**
     *签约
     */
    public function qianyue()
    {
        $datas = Db::name('shop')->where('dx_status',2)->where('dx_qian_status',0)
            ->field('shop_id,shop_account,merchantApplyType,dx_mch_id,dx_qian_err')->select();
//        dump($datas);die;
        if($datas){
            foreach ($datas as $k => $v){
                $traceLogId = "qian" . time() . $v['shop_id'];
                $config=array(
                    'traceLogId'=> $traceLogId,
                    'requestSystem'=> 'YXDPAY',
                    'agentMerchantCode'=> '3178036282859431',
                    'employeeId'=> '15961889367',
                    'merchantCode'=> $v['dx_mch_id'],
                    'merchantType'=> $v['merchantApplyType'] == 'COMPANY' ? 'ORG' : 'PERSON',
                    'solutionNo'=> $v['merchantApplyType'] == 'INDIVIDUAL_SELLER' ? 'PS11700' : 'PS10418',
                    'renewFlag'=> 'TRUE',
                    'beginDate'=> date('Y-m-d') . ' 00:00:00',
                    'endDate'=> date('Y-m-d',strtotime('+10 year')) . ' 00:00:00',
                    'accreditRecord'=> [
                        'authMerchantCode' => $v['dx_mch_id'],
                        'authDate' => date('Y-m-d') . ' 00:00:00',
                        'authPlatform' => 'YXDPAY',
                        'productName' => $v['merchantApplyType'] == 'INDIVIDUAL_SELLER' ? '无证聚合收款产品' : '聚合收款产品',
                        'agreementName' => '钱到啦业务特约商户服务协议.pdf',
                        'agreementUrl' => $this->uploadMediaTable('https://csdl.jintianjifen.cn/钱到啦业务特约商户服务协议.pdf',2)
                    ]
                );
                // 合并配置数据和订单数据
                $data=$config;
                ksort($data);
                $datastr = $this->arrayToStr($data);
                $datastr = urldecode($datastr);
                $strSign = $this->createSign($datastr);      //生成签名
                // 生成签名
                $data['sign']=$strSign;
                ksort($data);
                $xml=$this->arrayToStr2($data);
                $bestpayUrl = 'https://mapi.bestpay.com.cn/mapi/agent/merchantinput/productContract';
                $response=$this->getJavaParam($xml,$bestpayUrl);
//                dump($response);die;
                $result=json_decode($response,true);
                if(isset($result['success']) && $result['success']){
                    Db::name('shop')->where('shop_id',$v['shop_id'])->update([
                        'dx_qian_traceLogId' => $traceLogId,
                        'dx_qian_status' => 1,
                        'dx_qian_err' => ''
                    ]);
                }else{
                    if(isset($result['errorMsg']) && $v['dx_qian_err'] != $result['errorMsg']){
                        Db::name('shop')->where('shop_id',$v['shop_id'])->update([
                            'dx_qian_err' => $result['errorMsg']
                        ]);
                    }
                }
            }
        }
        exit();
    }
    /**
     *查询
     */
    public function qianchaxun()
    {
        $datas = Db::name('shop')->where('dx_qian_status',1)
            ->field('shop_id,shop_account,dx_qian_traceLogId,dx_mch_id,merchantApplyType,dx_qian_err')->select();
//        dump($datas);die;
        if($datas){
            foreach ($datas as $k => $v){
                $config=array(
                    'traceLogId'=> $v['dx_qian_traceLogId'],
                    'requestSystem'=> 'YXDPAY',
                    'agentMerchantCode'=> '3178036282859431',
                    'merchantCode'=> $v['dx_mch_id'],
                    'solutionNo'=> $v['merchantApplyType'] == 'INDIVIDUAL_SELLER' ? 'PS11700' : 'PS10418',
                );
                // 合并配置数据和订单数据
                $data=$config;
                ksort($data);
                $datastr = $this->arrayToStr($data);
                $strSign = $this->createSign($datastr);      //生成签名
                // 生成签名
                $data['sign']=$strSign;
                ksort($data);
                $xml=json_encode($data);
                $bestpayUrl = 'https://mapi.bestpay.com.cn/mapi/agent/merchantinput/queryProductSignResult';//接收xml数据的文件
                $response=$this->getJavaParam($xml,$bestpayUrl);
                $result=json_decode($response,true);
//                dump($result);die;
                if($result['success'] && $result['result'][0]['status'] == 'SUCCESS'){
                    Db::name('shop')->where('shop_id',$v['shop_id'])->update([
                        'dx_qian_status' => 2,
                        'dx_qian_err' => ''
                    ]);
                    $insert = [
                        'sc_shop_id' => $v['shop_id'],
                        'sc_status' => 3,
                        'sc_time' => date('Y-m-d H:i:s'),
                        'sc_dx_mch_status' => 2,
                        'sc_dx_mch_id' => $v['dx_mch_id'],
                    ];
                    $scid = Db::name('shop_copy')->where('sc_shop_id',$v['shop_id'])->value('sc_id');
                    if($scid){
                        Db::name('shop_copy')->where('sc_shop_id',$v['shop_id'])->update($insert);
                    }else{
                        Db::name('shop_copy')->insert($insert);
                    }

                }else{
                    if(isset($result['errorMsg']) && $v['dx_qian_err'] != $result['errorMsg']){
                        Db::name('shop')->where('shop_id',$v['shop_id'])->update([
                            'dx_qian_err' => $result['applyment_state_msg']
                        ]);
                    }
                }
            }
        }
        exit();
    }

    /**
     * 获取私钥
     * @return bool|resource
     */
    private static function getPrivateKey()
    {
        $privKey = self::$PRIVATE_KEY;
        return openssl_pkey_get_private($privKey);
    }
    /**
     * 获取公钥
     * @return bool|resource
     */
    private static function getPublicKey()
    {

        $publicKey = self::$PUBLIC_KEY;
        return openssl_pkey_get_public($publicKey);
    }
    /**
     * 创建签名
     * @param string $data 数据
     * @return null|string
     */
    public function createSign($data = '')
    {
        //  var_dump(self::getPrivateKey());die;
        if (!is_string($data)) {
            return null;
        }
        return openssl_sign($data, $sign, self::getPrivateKey(),OPENSSL_ALGO_SHA256 ) ? base64_encode($sign) : null;
    }

    /**
     * 验证签名
     * @param string $data 数据
     * @param string $sign 签名
     * @return bool
     */
    public function verifySign($data = '', $sign = '')
    {
        if (!is_string($sign) || !is_string($sign)) {
            return false;
        }
        return (bool)openssl_verify(
            $data,
            base64_decode($sign),
            self::getPublicKey(),
            OPENSSL_ALGO_SHA1
        );
    }
    /**
     * 数组转字符串
     * @param string $data 数据
     * @param string $sign 签名
     * @return bool
     */
    public function arrayToStr($data)
    {
        $datastr = '';
        foreach ($data as $k=>$v){
            if($v == null) $v = 'null';
            if(is_array($v)) {
                foreach ($v as $k2 => $v2){
                    if(is_array($v2)){
                        foreach ($v2 as $k3 => $v3){
                            $v[$k2][$k3] = urlencode($v3);
                        }
                    }else{
                        $v[$k2] = urlencode($v2);
                    }
                }
                $v = json_encode($v);
            }
            $datastr .= $k . '=' . $v . '&';
        }
        $datastr = trim($datastr,'&');
        return $datastr;
    }
    public function arrayToStr2($data)
    {
        $datastr = '{';
        foreach ($data as $k=>$v){
            if($v == null) $v = 'null';
            if(is_array($v)) {
                $v = json_encode($v);
                $datastr .= '"' . $k . '"' . ':\'' . $v . '\',';
            }else{
                $datastr .= '"' . $k . '"' . ':"' . $v . '",';
            }

        }
        $datastr = trim($datastr,',');
        $datastr .= '}';
        return $datastr;
    }
    /**
     * 获取Java得来的参并进行对应的翼支付的URL的操作
     * @return string
     */
    public  function getJavaParam($xml,$bestpayUrl)
    {
        $javaData = ['encryptDataSrc' => $xml];
        $url = 'http://encrypt.seawxx.top:9999/digitalSign/encrypt';
        $header[] = "Content-type: application/json";//定义content-type为xml,注意是数组
        $javaRes = https_request($url, json_encode($javaData), $method = 'POST', $header);
        $javaRes = json_decode($javaRes,true);
        $java = [];
        $java['merchantNo'] = '3178036418683176';
        $java['encryptData'] = $javaRes['encryptData'];
        $java['encryptKey'] = $javaRes['encryptKey'];
        $xml=json_encode($java);
        $header[] = "Content-type: application/json";//定义content-type为xml,注意是数组
        $header[] = 'Content-Length:' . strlen($xml);//定义content-type为xml,注意是数组
        $header[] = 'Expect: ';//定义content-type为xml,注意是数组
        $response = https_request($bestpayUrl, $xml, $method = 'POST', $header);
        return $response;
    }
    /**
     * 解密
     * @return string
     */
    public  function getBackResult($response)
    {
        $javaData = ['encryptDataSrc' => $response];
        $url = 'http://encrypt.seawxx.top:9999/digitalSign/decryptResponse';
        $header[] = "Content-type: application/json";//定义content-type为xml,注意是数组
        $javaRes = https_request($url, json_encode($javaData), $method = 'POST', $header);
        $javaRes = json_decode($javaRes,true);
        return $javaRes;
    }
}